<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">

      <el-form-item label="患者姓名" prop="patientName">
        <el-input
          v-model="queryParams.patientName"
          placeholder="请输入患者姓名"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="主治医生" prop="masterName"  v-if="showMaster">
        <el-input
          v-model="queryParams.masterName"
          placeholder="请输入主治医生姓名"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="评估医生" prop="doctorName"  v-if="showDoctor">
        <el-input
          v-model="queryParams.doctorName"
          placeholder="请输入评估医生姓名"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="评定表名" prop="assessName">
        <el-input
          v-model="queryParams.assessName"
          placeholder="请输入评定表名"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <!--      <el-form-item label="患者编号" prop="patientId">-->
      <!--        <el-input-->
      <!--          v-model="queryParams.patientId"-->
      <!--          placeholder="请输入患者编号"-->
      <!--          clearable-->
      <!--          size="small"-->
      <!--          @keyup.enter.native="handleQuery"-->
      <!--        />-->
      <!--      </el-form-item>-->

      <el-form-item label="任务状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择任务状态" clearable size="small">
          <!--          <el-option label="请选择字典生成" value=""/>-->
          <el-option
            v-for="dict in dict.type.pd_task_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>


    <el-table v-loading="loading" :data="dataList" @selection-change="handleSelectionChange" :default-sort = "{prop: 'taskId', order: 'descending'}" :row-style="changeRowStyle">
      <el-table-column label="序号" type="index" width="50" align="center"/>
      <el-table-column label="患者姓名" align="center" prop="patientName">
        <template slot-scope="scope">
          <router-link :to="'/patient/detail/' + scope.row.patientId" class="link-type">
            <span>{{ scope.row.patientName }}</span>
          </router-link>
        </template>
      </el-table-column>
      <el-table-column label="主治医生" align="center" prop="masterName"/>
      <el-table-column label="评估医生" align="center" prop="doctorName"/>
      <el-table-column label="评定表名" align="center" prop="assessName"/>
      <el-table-column label="任务状态" align="center" prop="status" width="100px">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.pd_task_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <!--      <el-table-column label="收费" align="center" prop="charge" width="100px">-->
      <!--        <template slot-scope="scope">-->
      <!--          {{scope.row.charge === "1"?'是':''}}-->
      <!--        </template>-->
      <!--      </el-table-column>-->
      <el-table-column label="任务分配时间" align="center" prop="createTime"></el-table-column>
      <el-table-column label="任务评定时间" align="center" prop="assessTime"></el-table-column>
      <!--      <el-table-column label="备注" align="center" prop="remark"/>-->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="data_add(scope.row)"
            v-hasPermi="['system:task:assess']"
          >{{ scope.row.status==5?'重新评定':'评定'}}
          </el-button>
          <!--          <el-button-->
          <!--            size="mini"-->
          <!--            type="text"-->
          <!--            icon="el-icon-document-copy"-->
          <!--            @click="handleDetail(scope.row)"-->
          <!--          >查看-->
          <!--          </el-button>-->
          <!--          </router-link>-->
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:task:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getListalive"
    />
  </div>
</template>

<script>

import {
  listTask,
  dayListTask,
  dayListTask14,
  weekListTask,
  weekListTask14,
  getTask,
  delTask,
  addTask,
  updateTask,
  listTaskalive,
  listTaskByDept
} from "@/api/gaoxin/taskdata";
import {getUserProfile} from "@/api/system/user";
import {listData} from "@/api/gaoxin/data";
import path from "path";
import {listUserDept} from "@/api/system/dept";

export default {
  name: "index",
  dicts: ['pd_task_status'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // task_data表格数据
      dataList: [],
      // 评定数据列表
      taskdata: [],
      patientName: '',
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        patientName: null,
        masterName: null,
        doctorId: null,
        doctorName: null,
        assessName: null,
        phase: null,
        status: null,
        createTime: null,
        clinicId: null,
      },
      updateParams:{
        taskId:'',
        status: 2
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {},
      //显示查询主治医生
      showMaster: true,
      //显示查询评估医生
      showDoctor: true,
    };
  },
  //首页点击跳转到这里时接收的 status 参数
  created() {
    this.getList();

  },
  methods: {
    /** 查询首页 评估（日）task_data列表 */
    getDayList14(){  //status = 1，4 和 2 分开查询
      this.loading = true;
      dayListTask14(this.queryParams).then(response => {
        this.dataList = response.rows;
        console.log('hahahahahahah',this.dataList)
        this.total = response.total;
        this.loading = false;
      })
    },
    getDayList(){
      this.loading = true;
      dayListTask(this.queryParams).then(response => {
        this.dataList = response.rows;
        this.total = response.total;
        this.loading = false;
      })
    },
    /** 查询首页 评估（周）task_data列表 */
    getWeekList14(){
      this.loading = true;
      weekListTask14(this.queryParams).then(response => {
        this.dataList = response.rows;
        this.total = response.total;
        this.loading = false;
      })
    },
    getWeekList(){
      this.loading = true;
      weekListTask(this.queryParams).then(response => {
        this.dataList = response.rows;
        this.total = response.total;
        this.loading = false;
      })
    },

    /** 查询全部task_data列表 */
    getList() {
      this.loading = true; //添加一个模糊的遮罩蒙版 用于查询数据回显的过度动画
      getUserProfile().then(res => {
        let role = res.roleGroup;
        let depts = res.deptGroup;

        let index1 = role.indexOf('管理员');
        let index2 = role.indexOf('高级角色');
        let index3 = role.indexOf('普通角色');

        if (index1 >= '0') {
          this.getListalive();
        } else if (index2 >= '0') {
          this.showMaster = false;
          for (let i = 0; i < depts.length; i++) {
            if (depts[i].senior == '1') {
              let deptId = depts[i].deptId;
              this.getListaliveByDept(deptId);
              break;
            }
          }
        } else if (index3 >= '0') {
          this.showDoctor = false;
          let userId = res.data.userId;
          this.getListaliveByUserId(userId);
        }
      });
    },

    /** 查询住院者task_data列表 */
    getListalive() {
      this.loading = true;
      listTaskalive(this.queryParams).then(response => {
        this.dataList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },

    getListaliveByUserId(userId) {
      this.loading = true;
      this.queryParams.doctorId = userId;
      listTaskalive(this.queryParams).then(response => {
        this.dataList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    getListaliveByDept(deptId) {
      this.loading = true;
      listTaskByDept(deptId).then(response => {
        this.dataList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        patientName: null,
        masterName: null,
        doctorName: null,
        assessName: null,
        taskId: null,
        patientId: null,
        masterId: null,
        doctorId: null,
        assessId: null,
        assessData: null,
        phase: null,
        status: "0",
        remark: null,
        charge:null,
        createTime: null,
        assessTime:null,
        updateTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.taskId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加任务";
    },
    /** 评定按钮操作 */
    data_add(row) {
      let taskId = row.taskId;
      let status = row.status;
      if (status == 1) {
        this.$router.push('/workflow/execute/detail/'+taskId);
        // this.$router.push({name: 'dataAdd', params: {taskdata: row, assessId: row.assessId}});
      }
      if (status == 2) {
        this.$modal.msgSuccess("已完成评定，请重新分配评定任务");
      }
      if (status == 3) {
        this.$modal.msgSuccess("已完成审核，无法进行评定");
      }
      if (status == 4 || status==5) {
        this.$router.push('/workflow/execute/detail/'+taskId);
        // this.$router.push({name: 'dataAdd', params: {taskdata: row,taskId:row.taskId}});
      }

    },
    /** 查看评定任务 */
    handleDetail(row) {
      let taskId = row.taskId;
      this.$router.push({name: 'datasShow', params: {taskId: taskId,}});
    },
    // handleDetail(row) {
    //   let taskId = row.taskId;
    //   this.$router.push('/gaoxin/taskdata-detail/index/' + taskId);
    // },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const taskId = row.taskId || this.ids
      getTask(taskId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "评定页面";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.taskId != null) {
            updateTask(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getListalive();
            });
          } else {
            addTask(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getListalive();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const taskIds = row.taskId || this.ids;
      const patient = row.patientName;
      const task = row.assessName;
      this.$modal.confirm(`是否删除患者${patient}的${task}评定任务及相关数据？`).then(function () {
        return delTask(taskIds);
      }).then(() => {
        this.getListalive();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/data/export', {
        ...this.queryParams
      }, `data_${new Date().getTime()}.xlsx`)
    },
    changeRowStyle({row}){
      //获取任务分配时间的时间戳，加24小时，单位秒
      let deadline=Date.parse( new Date(row.createTime) )+ 86400000
      let curTime=Date.parse(new Date())
      //超24小时且状态为待评估
      if(curTime>deadline && row.status==1){
        //解决多次请求message弹出多个弹框，弹一个就够了
        this.$message.closeAll();
        this.$message({
          dangerouslyUseHTMLString: true,
          message: '<h3>您有任务超过24小时未评定，请及时处理</h3>',
          type: 'error',
          offset:120
        });
        return {
          background:"#ff6a61"
        }
      }
    }
  }
};
</script>
